<?php

/**
 * Media Handler
 * @author ReGeDa
 */
class Media_Handler extends DB_Event_Handler {

	/**
	 * Get header "If-Modified-Since"
	 * @return integer
	 */
	private function if_modified_since() {
		return isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) 
					? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])
					: 0;
	}

	/**
	 * Get image type from file extension
	 * @param string $ext
	 * @return integer
	 */
	private function get_type_from_fext($ext) {
		if ($ext == 'png')
			return IMAGETYPE_PNG;
		if ($ext == 'gif')
			return IMAGETYPE_GIF;
		// jpeg
		return IMAGETYPE_JPEG;
	}

	/**
	 * Put common response header
	 * @param integer $modified
	 */
	private function put_cache_header($modified) {
		platcode()->plugins->import('HTTP')->set_header(array(
			'Pragma' => '',
			'Expires' => '',
			'Cache-Control' => '',
			'Last-Modified' => gmdate("D, d M Y H:i:s", $modified).' GMT'
		));
	}

	/**
	 * Output user picture
	 * @param string $filename
	 */
	public function on_userpic($filename) {
		if (preg_match('/^([a-f\d]+)\.(png|gif|jpeg)$/',$filename, $matches)) {

			// If-Modified-Since
			$modified_date = $this->if_modified_since();
			// image type as PHP constant
			$image_type = $this->get_type_from_fext($matches[2]);

			$AQ = &platcode()->plugins->import('ActiveQuery');
			/* @var $AQ ActiveQuery */

			$stmt = $this->db->prepare(
				$AQ
					->set(array(
						'path' => $matches[1],
						'frmt' => $image_type,
						'date' => $modified_date
					))
					->call('get_user_pic')
			);
			/* @var $stmt PDOStatement */

			$stmt->bindColumn(1, $state);
			$stmt->bindColumn(2, $load_date);
			$stmt->bindColumn(3, $handle, PDO::PARAM_LOB);

			try {

				$AQ->query($stmt);
				$stmt->fetch();
				
				$http = &platcode()->plugins->import('HTTP');
				/* @var $http HTTP */

				if ($state == -1) {
					// not found
					$http->set_response_code(404);
				}
				else {

					// not modified
					if ($state == 1) {
						
						$http->set_response_code(304);
						// send cache header
						$this->put_cache_header($modified_date);
					}
					// send image
					else {

						$bytes_stat = fstat($handle);

						$http->set_header(array(
							'Content-Type' => image_type_to_mime_type($image_type),
							'Content-Length' => $bytes_stat['size']
						));

						// send cache header
						$this->put_cache_header($load_date);

						fpassthru($handle);
					}
				}

			} catch (PDOException $e) {
				// no yet
			}

		}
		// exit
		platcode()->terminate();
	}

}

// end of file